<template>
    <div>
        <div v-if="conversationList.length > 0">
          <conversation-item v-for="conversationItem in conversationList" :key="conversationItem.account" :conversationItem="conversationItem" @click.native="toChat(conversationItem)"></conversation-item>
        </div>
        <div class="empty" v-if="conversationList.length == 0">
          <img :src="consultationEmpty" width="144px" height="136px">
          <div style="font-size: 15px;margin-top: 10px;color:#b3b3b3">暂无相关记录</div>
        </div>
    </div>
</template>

<script>
  import { mapGetters} from 'vuex';
  import { webim } from '../../assets/im/webim.js'
  import ConversationItem from './ConversationItem.vue';
  import imgMap from '../../../static/js/imgmap.js';
    export default {
        data() {
          return {
            loginInfo: {},
            conversationList: [],
            orgId: this.$route.query.orgId,
          }
        },

      components: {
        conversationItem: ConversationItem,
      },
      computed: {
        ...mapGetters(['loginData']),
          consultationEmpty() {
            return imgMap.consultationEmpty;
          },
      },

      methods: {
          imLogin() {
            this.loginInfo = {
              'sdkAppID': 1400034465, //用户所属应用id,必填
              'identifier': this.$store.getters.loginData.userObj.userId.value, //当前用户ID,必须是否字符串类型，必填
              'accountType': 12230, //用户所属应用帐号类型，必填
              'userSig': this.$store.getters.loginData.imUserSign
            };
            let onConnNotify = function (resp) {
              let info;
              switch (resp.ErrorCode) {
                case webim.CONNECTION_STATUS.ON:
                  webim.Log.warn('建立连接成功: ' + resp.ErrorInfo);
                  break;
                case webim.CONNECTION_STATUS.OFF:
                  info = '连接已断开，无法收到新消息，请检查下你的网络是否正常: ' + resp.ErrorInfo;
                  // alert(info);
                  webim.Log.warn(info);
                  break;
                case webim.CONNECTION_STATUS.RECONNECT:
                  info = '连接状态恢复正常: ' + resp.ErrorInfo;
                  // alert(info);
                  webim.Log.warn(info);
                  break;
                default:
                  webim.Log.error('未知连接状态: =' + resp.ErrorInfo);
                  break;
              }
            };

            //监听事件
            let listeners = {
              "onConnNotify": onConnNotify, //监听连接状态回调变化事件,必填
              "jsonpCallback": this.jsonpCallback, //IE9(含)以下浏览器用到的jsonp回调函数，
              "onMsgNotify": this.onMsgNotify, //监听新消息(私聊，普通群(非直播聊天室)消息，全员推送消息)事件，必填
              "onLongPullingNotify": function (data) {
                console.debug('onLongPullingNotify', data)
              }
            };

            //初始化时，其他对象，选填
            let options = {
              'isAccessFormalEnv': true, //是否访问正式环境，默认访问正式，选填
              'isLogOn': false //是否开启控制台打印日志,默认开启，选填
            };

            let vm = this;
            webim.login(
              this.loginInfo, listeners, options,
              function(resp) {
                vm.loginInfo.identifierNick = resp.identifierNick; //设置当前用户昵称
                vm.loginInfo.headurl = resp.headurl; //设置当前用户头像

                vm.getRecentContact();
              },
              function(err) {
                alert(err.ErrorInfo);
              }
            );
          },
          onMsgNotify(newMsgList) {
            this.getRecentContact();
          },

          //IE9(含)以下浏览器用到的jsonp回调函数
          jsonpCallback(rspData) {
            webim.setJsonpLastRspData(rspData);
          },

          getRecentContact() {
            let vm = this;
            let options = {
              'Count': 100 //要拉取的最近会话条数
            };
            // var sessMap = webim.MsgStore.sessMap();
            // console.log(sessMap);

            webim.getRecentContactList(
              options,
              function (resp) {
                // console.log(resp);
                let firstSessType; //保存第一个会话类型
                let firstSessId; //保存第一个会话id
                let ids = [];
                let imConversationList = [];
                if (resp.SessionItem && resp.SessionItem.length > 0) { //如果存在最近会话记录

                  for (let i in resp.SessionItem) {
                    let item = resp.SessionItem[i];
                    let type = item.Type; //接口返回的会话类型
                    let sessType, typeZh, sessionId, sessionNick = '',
                      sessionImage = '',
                      senderId = '';
                    if (type == webim.RECENT_CONTACT_TYPE.C2C) { //私聊
                      typeZh = '私聊';
                      sessType = webim.SESSION_TYPE.C2C; //设置会话类型
                      sessionId = item.To_Account; //会话id，私聊时为好友ID或者系统账号（值为@TIM#SYSTEM，业务可以自己决定是否需要展示），注意：从To_Account获取,
                      if (sessionId == '@TIM#SYSTEM') { //先过滤系统消息，，
                        webim.Log.warn('过滤好友系统消息,sessionId=' + sessionId);
                        continue;
                      }
                      sessionNick = item.C2cNick; //会话昵称，如果昵称为空，默认将其设成会话id
                      sessionImage = item.C2cImage;
                      senderId = item.To_Account;
                    } else if (type == webim.RECENT_CONTACT_TYPE.GROUP) { //群聊
                      continue;  //TODO  暂时屏蔽群消息

                      typeZh = '群聊';
                      sessType = webim.SESSION_TYPE.GROUP; //设置会话类型
                      sessionId = item.ToAccount; //会话id，群聊时为群ID，注意：从ToAccount获取
                      sessionNick = item.GroupNick; //会话昵称，群聊时，为群名称，接口一定会返回
                      sessionImage = item.GroupImage;
                      senderId = item.MsgGroupFrom_Account; //群消息的发送者id
                      if (!senderId) { //发送者id为空
                        webim.Log.warn('群消息发送者id为空,senderId=' + senderId + ",groupid=" + sessionId);
                        continue;
                      }
                      if (senderId == '@TIM#SYSTEM') { //先过滤群系统消息，因为接口暂时区分不了是进群还是退群等提示消息，
                        webim.Log.warn('过滤群系统消息,senderId=' + senderId + ",groupid=" + sessionId);
                        continue;
                      }
                    } else {
                      typeZh = '未知类型';
                      sessionId = item.ToAccount; //
                    }
                    if (!sessionId) { //会话id为空
                      webim.Log.warn('会话id为空,sessionId=' + sessionId);
                      continue;
                    }

                    if (sessionId == '@TLS#NOT_FOUND') { //会话id不存在，可能是已经被删除了
                      webim.Log.warn('会话id不存在,sessionId=' + sessionId);
                      continue;
                    }


                    if (!firstSessId) {
                      firstSessType = sessType; //记录第一个会话类型
                      firstSessId = sessionId; //记录第一个会话id
                    }
                    imConversationList.push({
                      SessionType: sessType, //会话类型
                      SessionId: sessionId, //会话对象id，好友id或者群id
                      SessionNick: sessionNick, //会话昵称，好友昵称或群名称
                      SessionImage: sessionImage, //会话头像，好友头像或者群头像
                      C2cAccount: senderId, //发送者id，群聊时，才有用
                      UnreadMsgCount: item.UnreadMsgCount, //未读消息数,私聊时需要通过webim.syncMsgs(initUnreadMsgCount)获取,参考后面的demo，群聊时不需要。
                      MsgSeq: item.MsgSeq, //消息seq
                      MsgRandom: item.MsgRandom, //消息随机数
                      MsgTimeStamp: webim.Tool.formatTimeStamp(item.MsgTimeStamp), //消息时间戳
                      MsgGroupReadedSeq: item.MsgGroupReadedSeq || 0,
                      MsgShow: item.MsgShow //消息内容,文本消息为原内容，表情消息为[表情],其他类型消息以此类推
                    });
                    ids.push(sessionId);
                  }
                }
                if(ids.length > 0) {
                    vm.netConversationGet(ids, imConversationList);
                }
              },
            );
          },

          netConversationGet(ids, imConversationList) {
            let request = {
              accounts: ids,
              orgId: this.orgId
            };
            let vm = this;
            this.$store.dispatch("imConversationList", request).then((dataList) => {
              if(dataList && dataList.length > 0) {
                vm.conversationList = dataList;
                if(imConversationList && imConversationList.length > 0) {
                  for (let i = 0; i < dataList.length; i++) {
                      let netData = dataList[i];
                      for (let j = 0; j < imConversationList.length; j++) {
                        let imData = imConversationList[j];
                        if(netData.account == imData.SessionId) {
                          netData.conversation = imData;
                          break;
                        }
                      }
                  }
                }
              }
            }).catch(error => {
              this.$toast(error.message);
            });
          },

        toChat(conversationItem) {
          this.$router.push({
            path: "chat",
            query: {userId: conversationItem.account, drName: conversationItem.nick, friendHeadUrl: conversationItem.faceUrl, gender: conversationItem.gender.value}
          })
        },
        //获取聊天记录
        getImChatData() {
            let request = {
              chatuser: '1098738383691227100', //this.$store.getters.loginData.userObj.userId.value
            };
            let vm = this;
            this.$store.dispatch("imChatData", request).then((dataList) => {
              // if(dataList && dataList.length > 0) {
              //   vm.conversationList = dataList;
              //   if(imConversationList && imConversationList.length > 0) {
              //     for (let i = 0; i < dataList.length; i++) {
              //         let netData = dataList[i];
              //         for (let j = 0; j < imConversationList.length; j++) {
              //           let imData = imConversationList[j];
              //           if(netData.account == imData.SessionId) {
              //             netData.conversation = imData;
              //             break;
              //           }
              //         }
              //     }
              //   }
              // }
            }).catch(error => {
              this.$toast(error.message);
            });
          },

      },

      created() {
        // this.getImChatData();
        // this.imLogin();
        // console.log('localStorage.getItem("imMsgList")==',localStorage.getItem("imMsgList"));
      }
    }
</script>

<style scoped>
.empty {
  padding: 50px 40px;
  text-align: center;
}
</style>
